const app = getApp()

Page({
  data: {
    theme: 'light',
    post: null,
    user: null,
    loading: false,
    onGlobalUserChange: null,
    content: ''
  },
  onLoad() {
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.on('init', ({post}) => {
      this.setData({ post })
    })

    this.setData({
      theme: wx.getSystemInfoSync().theme || 'light',
      user: app.globalData.user
    })
    this.data.onGlobalUserChange = this.onGlobalUserChange.bind(this)
    app.watch('user', this.data.onGlobalUserChange)
    if (wx.onThemeChange) {
      wx.onThemeChange(({theme}) => {
        this.setData({theme})
      })
    }
  },
  onUnload() {
    app.unWatch('user', this.data.onGlobalUserChange)
  },
  onGlobalUserChange(user) {
    this.setData({ user })
  },
  back() {
    wx.navigateBack()
  },
  onContentChange(e) {
    this.setData({
      content: e.detail.value?.substr(0, 499)
    })
  },
  // onChange(e) {
  //   const value = +e.detail.value
  //   this.setData({
  //     value
  //   })
  //   this.getOpenerEventChannel().emit('change', value)
  //   this.back()
  // },
  getUserInfoOnSubmit(e) {
    this.setData({
      loading: true
    })
    app.registerUser(e.detail.userInfo)
    .then((user) => {
      this.data.user = user
      this.submit()
    })
    .finally(() => {
      this.setData({
        loading: false
      })
    })
  },
  submit() {
    wx.requestSubscribeMessage({
      tmplIds: ['AC3OZlKk4-S8m1m_RcqAx4fj5hvZ4jRZj9qAovye-zQ'],
    })
    .finally(() => {
      this.setData({
        loading: true
      })
      const { post, user, content } = this.data
      wx.cloud.callFunction({
        name: 'flow',
        data: {
          action: 'insert',
          data: {
            content,
            post: {
              _id: post._id,
              title: post.title,
              content: post.content,
              labels: post.labels,
              medias: post.medias,
            },
            to: {
              openid: post.openid,
              nickName: post.nickName,
              avatarUrl: post.avatarUrl
            },
            from: {
              openid: user.openid,
              nickName: user.nickName,
              avatarUrl: user.avatarUrl
            },
          }
        },
      })
      .then(() => {
        this.back()
      })
      .finally(() =>{
        this.setData({
          loading: false
        })
      })
    })
    
  },
  onShareAppMessage() {
    return {
      title: '东鸣西应',
      path: '/page/home/index'
    }
  },
})
